import { convert } from 'xmlbuilder2'
const psCore = require('photoshop').core

// constants
  const prefix = 'sample'
   const  key = 'fileId'
   const namespace = 'https://forums.creativeclouddeveloper.com/t/uxp-batchplay-setxmp-data/5956/4'

interface XmpMetaObject {
  'x:xmpmeta': {
    'rdf:RDF': {
      'rdf:Description': {
        '@xmlns': {
          [key: string]: string
        }
        [key: string]:
          | string
          | {
              [key: string]:
                | string
                | number
                | {
                    [key: string]: string | number
                  }
            }
      }
    }
  }
}

// call to fetch documentXMP
let getDocumentXMP = async () => {
  try {
    async function fetchDocumentXmp() {
      return await require('photoshop').action.batchPlay(
        [
          {
            _obj: 'get',
            _target: {
              _ref: [
                { _property: 'XMPMetadataAsUTF8' },
                { _ref: 'document', _enum: 'ordinal', _value: 'targetEnum' },
              ],
            },
          },
        ],
        { synchronousExecution: true },
      )[0].XMPMetadataAsUTF8
    }

    return await require('photoshop').core.executeAsModal(fetchDocumentXmp, {
      command: 'setting document xmp',
    })
  } catch (error) {
    console.error('error fetching document xmp')
// optional. shows an alert to the user.
      psCore.showAlert({ message: 'error fetching document xmp ', error })
  }
}

// Set  the Doc XMP for file
const setDocumentXMP = async (xmpString: any) => {
  function setXmpDocumentBatchPlayM() {
    require('photoshop').action.batchPlay(
      [
        {
          _obj: 'set',
          _target: [
            { _ref: 'property', _property: 'XMPMetadataAsUTF8' },
            { _ref: 'document', _enum: 'ordinal', _value: 'targetEnum' },
          ],
          to: {
            _obj: 'document',
            XMPMetadataAsUTF8: xmpString,
          },
        },
      ],
      {},
    )
  }

  try {
    let results = await require('photoshop').core.executeAsModal(
      setXmpDocumentBatchPlayM,
      {
        command: 'setting document xmp',
      },
    )

    return results
  } catch (error) {
    console.error('Error setting document XMP ', error)
   // optional. show an alert to user
   psCore.showAlert({ message: 'Error setting document xmp ', error })
  }
}

// Fetch document xmp keys

export const getDocumentXmpData = async () => {
 

  const xmpString = await getDocumentXMP()
  const obj = convert(xmpString, {
    format: 'object',
  }) as unknown as XmpMetaObject

  return (
    obj['x:xmpmeta']['rdf:RDF']['rdf:Description'][`${prefix}:${key}`] ||
    'nothing'
  )
}

// set document metadata
export const setDocumentXmp = async ( value : string) => {
  try { 

    const xmpString = await getDocumentXMP()

    const obj: any = convert(xmpString, {
      format: 'object',
    })

    obj['x:xmpmeta']['rdf:RDF']['rdf:Description'][`@xmlns:${prefix}`] =
      namespace
    obj['x:xmpmeta']['rdf:RDF']['rdf:Description'][`${prefix}:${key}`] = value

    const newXmpString = convert(obj, { format: 'xml' })

     await setDocumentXMP(newXmpString)
    
  } catch (error) {
    console.log('Error set Document xmp metData ', error)
psCore.showAlert({ message: 'Error set Document xmp metData ', error })
  }
}